package com.feng.handler.securtity;

import com.alibaba.fastjson.JSON;
import com.feng.domain.ResponseResult;
import com.feng.domain.enums.AppHttpCodeEnum;
import com.feng.util.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器,写完后需要配置到security配置类中
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
       e.printStackTrace();
       //BadCredentialsException 用户名或密码不正确
        //InsufficientAUthenticationException 用户需要登录
        ResponseResult result=null;
        if(e instanceof BadCredentialsException){
             result= ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),e.getMessage());

        }
        else if(e instanceof InsufficientAuthenticationException){
            result=ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        else{
            result=ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR,"认证或授权失败");
        }

       String s = JSON.toJSONString(result);
       //响应给前端
        WebUtils.renderString(httpServletResponse,s);



    }
}
